package com.culturalCenter.dataCenter.globalconfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步处理定时任务的线程池
 *
 * @author ISMC
 * @since 2021/3/3 10:56
 */
@Configuration
public class ExecutorConfig {

    private int corePoolSize = 10;
    private int maxPoolSize = 100;
    private int queueCapacity = 1000;
    private int keepAliveSeconds = 30000;
    private int awaitTerminationMillis = 30000;

    @Bean
    public Executor dataThreadExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setThreadNamePrefix("DataThread-");
        // 获取服务器的cpu内核
        int i = Runtime.getRuntime().availableProcessors();
        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
        // 缓冲队列容量
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        // 线程空闲时间
        threadPoolTaskExecutor.setKeepAliveSeconds(keepAliveSeconds);
        threadPoolTaskExecutor.setAwaitTerminationMillis(awaitTerminationMillis);
        // 配置拒绝策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolTaskExecutor;
    }

}
